<?php


namespace app\admin\controller\jizhan;


use app\admin\model\HtnsBasestationStore;
use app\admin\model\HtnsOrder;
use app\admin\model\HtnsOrderCartInfo;
use app\admin\model\HtnsSystemCity;
use app\admin\model\HtnsUser;
use app\admin\traits\Curd;
use app\api\services\QrcodeService;
use app\api\services\StoreService;
use app\api\services\TengxunMap;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use think\App;
use think\Exception;
use think\facade\Cache;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="基站门店")
 */
class Store extends AdminController
{

    use Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new HtnsBasestationStore();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index($export = 0)
    {
        if ($this->request->isAjax() || $export) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 自定义搜索条件解析
            $whereArr = [];
            $filter   = input('filter');
            $filter = htmlspecialchars_decode($filter);// html特殊字符转化&quot;转换为'
            if ($filter) {
                $filterArr = json_decode($filter, true);
//                if (isset($filterArr['storeName'])) {
//                    $whereArr[] = ['store_id', '=', $filterArr['storeName']];
//                }
//                if (isset($filterArr['payType'])) {
//                    $whereArr[] = ['pay_type', '=', $filterArr['payType']];
//                }
//                if (isset($filterArr['orderStatus'])) {
//                    $whereArr[] = ['status', '=', $filterArr['orderStatus']];
//                }
//                if (isset($filterArr['add_time'])) {
//                    $time       = explode(' - ', $filterArr['add_time']);
//                    $whereArr[] = ['add_time', 'between', [strtotime($time[0]), strtotime($time[1])]];
//                }
            }
//            halt($filter,$whereArr);
            if($export){
                $page = 1;
                $limit = 10000;
            }
            $whereArr = $where;
            $count = $this->model
                ->where($whereArr)
                ->count();
            $list  = $this->model
                ->where($whereArr)
                ->page($page, $limit)
                ->order($this->sort)
//                ->fetchSql(true)
                ->select()->toArray();
            // 导出
            if($export){
                return $list;
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {

                if($post['is_main']){
                    $storeService = new StoreService();
                    $mainStore = $storeService->getMainStore();
                    if($mainStore){
                        $this->error('主店已存在,不能再添加加主店!');
                    }
                }

                $provinceArr = explode('-',$post['province']);
                $post['province'] = $provinceArr[1];

                $cityArr = explode('-',$post['city']);
                $post['city'] = $cityArr[1];

                $districtArr = explode('-',$post['district']);
                $post['district'] = $districtArr[1];

                $post['address'] = $post['province'].$post['city'].$post['district'].$post['address'];
                // 根据详细地址查询经纬度
                $tengxunMap = new TengxunMap();
                $res = $tengxunMap->addressToLatlng($post['address']);
                if($res['code']){
                    $data = $res['data'];
                    $post['lng'] = $data['lng'];
                    $post['lat'] = $data['lat'];
                }else{
                    $this->error('保存失败,地址查询经纬度失败:' . $res['msg']);
                }
                $save               = $this->model->save($post);

                $storeId = $this->model->id;
                $storeName = $this->model->name;
                $qrcodeService = new QrcodeService();
                $page = 'pages/users/login/new_login';//登录注册页面
//                $page = 'pages/index/index';//首页路径
                $dataStr = 'store_id='.$storeId.'&type=scan';//数据
                $fileName = date('YmdHis').'_store_'.$storeId.'.png';//文件名称
                $qrcode = $qrcodeService->makeXcxUnlimitQrcode($page , $dataStr , $fileName);
                if($qrcode){
                    $where['id'] = $storeId;
                    $dataQ['qrcode'] = $qrcode;
                    HtnsBasestationStore::where($where)->update($dataQ);
                }
            } catch (Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                if($post['is_main']){
                    $storeService = new StoreService();
                    $mainStore = $storeService->getMainStore();
                    if($mainStore && $mainStore['id'] != $id){
                        $this->error('主店已存在,不能再修改为主店!');
                    }
                }

                $provinceArr = explode('-',$post['province']);
                $post['province'] = $provinceArr[1];

                $cityArr = explode('-',$post['city']);
                $post['city'] = $cityArr[1];

                $districtArr = explode('-',$post['district']);
                $post['district'] = $districtArr[1];

                $address = $post['province'].$post['city'].$post['district'].$post['address'];
                // 根据详细地址查询经纬度
                $tengxunMap = new TengxunMap();
                $post['address'] = trim($post['address']);
//                echo 'address<pre>';print_r($post['address']);die;
                $res = $tengxunMap->addressToLatlng($address);
                if($res['code']){
                    $data = $res['data'];
                    $post['lng'] = $data['lng'];
                    $post['lat'] = $data['lat'];
                }else{
                    $this->error('保存失败,地址查询经纬度失败:' . $res['msg']);
                }
                // 修改门店名称,重新生成二维码
                if($post['name']){
                    $qrcodeService = new QrcodeService();
//                    $page = 'pages/index/index';//首页路径
                    $page = 'pages/users/login/new_login';//登录注册页面
                    $dataStr = 'store_id='.$row['id'].'&type=scan';//数据
                    $fileName = date('YmdHis').'_store_'.$row['id'].'.png';//文件名称
                    $qrcode = $qrcodeService->makeXcxUnlimitQrcode($page , $dataStr , $fileName);
                    if($qrcode){
                        $post['qrcode'] = $qrcode;
                    }
//                    $dataArr['type'] = 'scan';
//                    $dataArr['data']['store_id'] = $row['id'];
//                    $dataArr['data']['store_name'] = $post['name'];
//                    $qrcodeUrl = $qrcodeService->makeQrcode($dataArr);
//                    if($qrcodeUrl){
//                        $post['qrcode'] = $qrcodeUrl;
//                    }
                }
                $save = $row->save($post);
            } catch (Exception $e) {
                $this->error('保存失败-'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        // 查询组装数据
        $where['name'] = $row['province'];
        $city = HtnsSystemCity::where($where)->find();
        if($city){
            $row['province'] = $city['city_id'].'-'.$row['province'];
            Cache::set('provinceId',$city['city_id'],3600);
        }
        $where['name'] = $row['city'];
        $where['level'] = 1;
        $city = HtnsSystemCity::where($where)->find();
        if($city){
            $row['city'] = $city['city_id'].'-'.$row['city'];
            Cache::set('cityId',$city['city_id'],3600);
        }
        $where['name'] = $row['district'];
        $where['level'] = 2;
        $city = HtnsSystemCity::where($where)->find();
        if($city){
            $row['district'] = $city['city_id'].'-'.$row['district'];
            Cache::set('districtId',$city['city_id'],3600);
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    // 获取城市列表
    /**
     * @NodeAnotation(title="获取城市列表")
     */
    public function getProvince()
    {
        $ret['code'] = 1;
        $ret['msg']  = '获取成功';
        $ret['data'] = [];

        $htnsSystemCity = new HtnsSystemCity();
        $res            = $htnsSystemCity->getProvince();
        if ($res) {
            foreach ($res as &$v) {
                $v['city_id'] = $v['city_id'] . '-' . $v['name'];
            }
            $ret['data'] = $res;
        }
        return json($ret);
    }

    // 获取市列表
    /**
     * @NodeAnotation(title="获取市列表")
     */
    public function getCity()
    {
        $provinceId = input('provinceId');
        $format     = input('format');// 格式
        if(empty($provinceId)){
            $provinceId = Cache::get('provinceId');
        }
        $htnsSystemCity = new HtnsSystemCity();
        $res            = $htnsSystemCity->getCity($provinceId);
        if ($res) {
            if ($format == 'html') {
                $rest = '';
                $cityId = Cache::get('cityId');
                foreach ($res as $v) {
                    $selected = '';
                    if($v['city_id'] == $cityId) {
                        $selected = 'selected';
                    }
                    $rest .= '<option value="' . $v['city_id'] . '-' . $v['name'] . '" '.$selected.'>' . $v['name'] . '</option>';
                }
                return $rest;
            }
        }
        return json($res);
    }

    // 获取区列表
    /**
     * @NodeAnotation(title="获取区列表")
     */
    public function getArea()
    {
        $cityId         = input('cityId');
        $format         = input('format');// 格式
        if(empty($cityId)){
            $cityId = Cache::get('cityId');
        }
        $htnsSystemCity = new HtnsSystemCity();
        $res            = $htnsSystemCity->getArea($cityId);
        if ($res) {
            if ($format == 'html') {
                $rest = '';
                $districtId = Cache::get('districtId');
                foreach ($res as $v) {
                    $selected = '';
                    if($v['city_id'] == $districtId) {
                        $selected = 'selected';
                    }
                    $rest .= '<option value="' . $v['city_id'] . '-' . $v['name'] . '" '.$selected.'>' . $v['name'] . '</option>';
                }
                return $rest;
            }
        }
        return json($res);
    }

    /**
     * @NodeAnotation(title="门店列表")
     */
    public function getList()
    {
        $ret['code'] = 1;
        $ret['msg']  = '获取成功';
        $ret['data'] = [];
        $storeService = new StoreService();
        $res = $storeService->getList();
        if($res){
            $ret['data'] = $res;
        }
        return json($ret);
    }
}